package nckd.wnqjt.tmc.tda.plugin.form;

import com.alibaba.fastjson.JSON;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.qing.*;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 结算金额轻分析报表（集团）
 */

public class TlementAmountCliqueQingQueryPlugin extends AbstractFormPlugin implements IQingDataProvider {


    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cas_recbill";
        QingMeta meta = new QingMeta();
        EntryEntity entity1 = new EntryEntity();
        entity1.setKey(entityKey);
        entity1.setName(new LocaleString("收款处理"));
        entity1.setPkFieldName("id");
        meta.addEntryEntity(entity1);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("inflow");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Number.toNumber()); //数据类型	是
        column.setName(new LocaleString("本月流入")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("outflow");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("本月流出"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("claninflow");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("本月净流入"));
        meta.addColumn(column);

        /*column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.DateTime.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);*/

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("组织"));
        meta.addColumn(column);
        return meta;
    }

    @Override
    public QingData getData(String s, int startRow, int i1) {
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }
        QFilter[] billFilters = null;
        //单据状态=审核
        QFilter qFilter1 = new QFilter("billstatus", QCP.equals,"D");
        //结算方式为空
        QFilter settletnumberFilter = new QFilter("settletnumber", QCP.not_equals,"1");
        /**
         * 查询所有业务单元
         */
        ArrayList<Object> ids = new ArrayList<>();
        DynamicObject[] customerOrg = BusinessDataServiceHelper.load("bd_customer", "id,internal_company", new QFilter[]{new QFilter("internal_company",QCP.is_notnull,null).and("internal_company",QCP.not_equals,0)});
        if (customerOrg.length > 0) {
            Arrays.asList(customerOrg).forEach(t->{
                ids.add(t.getPkValue());
            });
        }
        DynamicObject[] supplierOrg = BusinessDataServiceHelper.load("bd_supplier", "id,internal_company", new QFilter[]{new QFilter("internal_company",QCP.is_notnull,null).and("internal_company",QCP.not_equals,0)});
        if (supplierOrg.length > 0) {
            Arrays.asList(supplierOrg).forEach(t->{
                ids.add(t.getPkValue());
            });
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String formatData = simpleDateFormat.format(cal.getTime());
        Date oldDate = null;
        Date nowDate = null;
        try {
            oldDate = simpleDateFormat.parse(formatData);
            nowDate = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        /*
        收款单
         */
        QFilter dateQf = new QFilter("payeedate", QCP.large_equals, oldDate).and(new QFilter("payeedate", QCP.less_equals, nowDate));
        QFilter qFilter2 = new QFilter("payer", QCP.not_in,ids);//剔除内部交易
        billFilters = new QFilter[]{qFilter1,qFilter2,dateQf,settletnumberFilter};
        String recBillFiled = "id,billstatus,actrecamt,settletnumber,org,org.id as recOrgId,org.name as orgName,payeedate,payer";
        DataSet recBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_recbill", recBillFiled, billFilters, null);
        recBillData = recBillData.groupBy(new String[]{"orgName","recOrgId"}).sum("actrecamt").finish();

        /*
        付款单
         */
        dateQf = new QFilter("paydate", QCP.large_equals, oldDate).and(new QFilter("paydate", QCP.less_equals, nowDate));
        qFilter2 = new QFilter("payee", QCP.not_in,ids);//剔除内部交易
        billFilters = new QFilter[]{qFilter1, qFilter2,dateQf,settletnumberFilter};
        String payBillFiled = "id,billstatus,settletnumber,org,org.id as payOrgId,org.name as orgName,payee,paydate,actpayamt";//nckd_sourcebilltype,
        DataSet payBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_paybill", payBillFiled, billFilters, null);
        payBillData = payBillData.groupBy(new String[]{"orgName","payOrgId"}).sum("actpayamt").finish();
        /*
        代发单
         */
        String agentBillFiled = "id,billstatus,actpayamount,settletnumber,org,org.id as agentOrgId,org.name as orgName,paytime";
        dateQf = new QFilter("paytime", QCP.large_equals, oldDate).and(new QFilter("paytime", QCP.less_equals, nowDate));
        billFilters = new QFilter[]{qFilter1,dateQf,settletnumberFilter};
        DataSet agentBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_agentpaybill", agentBillFiled, billFilters, null);
        agentBillData.groupBy(new String[]{"orgName","agentOrgId"}).sum("actpayamount").finish();

        /*
        业务单元
         */
        String orgFiled = "id,name,orgpattern,orgpattern.name";
        DataSet orgBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bos_org", orgFiled, null, null);

        DataSet dataSet = orgBillData.leftJoin(recBillData).on("id", "recOrgId").select(new String[]{"id", "name"},new String[]{"recOrgId","actrecamt"}).finish();
        DataSet dataSet1 = dataSet.leftJoin(payBillData).on("id","payOrgId").select(new String[]{"id","name","actrecamt"},new String[]{"payOrgId","actpayamt"}).finish();
        DataSet dataSet2 = dataSet1.leftJoin(agentBillData).on("id","agentOrgId").select(new String[]{"id","name","actrecamt","actpayamt"},new String[]{"agentOrgId","actpayamount"}).finish();

        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            dataindex.put("id", 0);
            dataindex.put("inflow", 1);
            dataindex.put("outflow", 2);
            dataindex.put("claninflow", 3);
            dataindex.put("orgName", 4);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            while (dataSet2.hasNext()) {
                Row row = dataSet2.next();
                Object[] obj = new Object[5];
                obj[0] = row.getLong("id");
                BigDecimal actrecamt = row.getBigDecimal("actrecamt") == null ? BigDecimal.ZERO : row.getBigDecimal("actrecamt");
                BigDecimal actpayamt = row.getBigDecimal("actpayamt") == null ? BigDecimal.ZERO : row.getBigDecimal("actpayamt");
                BigDecimal actpayamount = row.getBigDecimal("actpayamount") == null ? BigDecimal.ZERO : row.getBigDecimal("actpayamount");
                obj[1] = actrecamt;
                obj[2] = actpayamt.add(actpayamount);
                //Timestamp timestamp = (Timestamp) row.get("bizdate");
                //long time = timestamp.getTime();
                obj[3] = actrecamt.subtract(actpayamt.add(actpayamount));
                obj[4] = row.getString("name");
                rows.add(obj);
            }
            data.setRows(rows);
        }
        return data;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }


}
